package com.api.demo.service.impl;

import com.api.demo.entity.Content;
import com.api.demo.entity.UserContentHistory;
import com.api.demo.entity.UserFollow;
import com.api.demo.mapper.ContentMapper;
import com.api.demo.mapper.UserContentHistoryMapper;
import com.api.demo.mapper.UserFollowMapper;
import com.api.demo.service.ContentRecommendService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ContentRecommendServiceImpl extends ServiceImpl<ContentMapper, Content>
        implements ContentRecommendService {

    @Autowired
    private UserContentHistoryMapper historyMapper;

    @Autowired
    private UserFollowMapper userFollowMapper;

    @Override
    public Page<Content> getRecommendations(Long userId, Page<Content> page) {
        // 1. 获取用户已浏览的内容ID列表
        List<Long> viewedContentIds = getViewedContentIds(userId);

        // 2. 构建查询条件
        QueryWrapper<Content> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1) // 只查询已发布的内容
                .notIn(!viewedContentIds.isEmpty(), "id", viewedContentIds) // 排除已浏览内容
                .orderByDesc("like_count") // 按点赞数降序
                .orderByDesc("create_time");

        // 3. 分页查询
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Transactional
    @Override
    public void recordContentView(Long userId, Long contentId) {
        // 检查是否已有记录
        UserContentHistory history = historyMapper.selectOne(new QueryWrapper<UserContentHistory>()
                .eq("user_id", userId)
                .eq("content_id", contentId));

        if (history != null) {
            // 更新现有记录
            history.setViewCount(history.getViewCount() + 1);
            history.setLastViewTime(LocalDateTime.now());
            historyMapper.updateById(history);
        } else {
            // 创建新记录
            history = new UserContentHistory();
            history.setUserId(userId);
            history.setContentId(contentId);
            history.setViewCount(1);
            history.setLastViewTime(LocalDateTime.now());
            history.setCreateTime(LocalDateTime.now());
            history.setUpdateTime(LocalDateTime.now());
            historyMapper.insert(history);
        }
    }

    private List<Long> getViewedContentIds(Long userId) {
        return historyMapper.selectList(new QueryWrapper<UserContentHistory>()
                .select("content_id")
                .eq("user_id", userId))
                .stream()
                .map(UserContentHistory::getContentId)
                .collect(Collectors.toList());
    }

    private List<Long> getFollowContentIds(Long userId) {
        return userFollowMapper.selectList(new QueryWrapper<UserFollow>()
                .select("following_id")
                .eq("follower_id", userId))
                .stream()
                .map(UserFollow::getFollowingId)
                .collect(Collectors.toList());
    }

    @Override
    public Page<Content> getFollowContent(Long userId, Page<Content> page) {
        List<Long> followedUserIds = getFollowContentIds(userId); // 获取关注用户ID列表

        // 如果没有关注任何人，直接返回空分页
        if (followedUserIds.isEmpty()) {
            return new Page<>(page.getCurrent(), page.getSize(), 0);
        }

        QueryWrapper<Content> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)
                .in("user_id", followedUserIds) // 直接使用IN条件
                .orderByDesc("like_count");

        return baseMapper.selectPage(page, queryWrapper);
    }
}